<template>
  <div class="photo">
    <el-scrollbar height="100vh" @scroll="handleScroll" ref='scrollbarRef'>
      <WaterfallList :list="data.list" @ok="handleOk">
        <template #item="{ item }">
          <div class="item">
            <!-- 实际图片（默认隐藏） -->
            <img
              v-show="item.loaded"
              :src="item.url"
              :style="{ height: item.height + 'px' }"
              class="imgbg"
              @load="() => handleImageLoad(item)"
              @click="$preview(item.url)"
            />
            <!-- 加载占位图（默认显示） -->
            <img
              v-show="!item.loaded"
              src="/loading.gif"
              :style="{ height: item.height + 'px' }"
              class="imgbg"
            />
          </div>
        </template>
      </WaterfallList>
      <svg class="icon btn" aria-hidden="true" v-if="isshowdong" @click="handleTop">
        <use xlink:href="#icon-fanhuidingbu"></use>
      </svg>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import { useHomeStore } from "@/stores/home.js";
import URL from "@/api/url";
import axios from "axios";

const waterfallRef = ref();
const store = useHomeStore();
const scrollbarRef = ref()
const currentScrollbarHeight = ref(0)
const isshowdong = ref(false)
const data = reactive({
  list: [],
  refreshFn: null,
});
const handleOk = (fn) => {
  data.refreshFn = fn;
};

// 图片加载完成处理
const handleImageLoad = (item) => {
  item.loaded = true;
  nextTick(() => {
    data.refreshFn?.(); // 重新计算瀑布流布局
  });
};

function photo() {
  axios.get(URL() + "/photo/findPhoto").then((response) => {
    if (response.data.code === 20000) {
      store.imgUrl = response.data.data;
      store.imgUrl.forEach((item) => {
        data.list.push({
          url: item.imgUrl,
          height: item.height,
          loaded: false // 初始状态为未加载
        });
       
      });
    }
  });
}

onMounted(() => {  
  photo();
});

const handleScroll = (a) => {
  currentScrollbarHeight.value = a.scrollTop
  isshowdong.value = a.scrollTop !== 0
}

const handleTop = () => {
  let tempHeight = currentScrollbarHeight.value
  let perDecrementHeight = tempHeight / 60
  let timer = setInterval(() => {
    tempHeight -= perDecrementHeight
    if (tempHeight <= 0) {
      scrollbarRef.value.setScrollTop(0)
      clearInterval(timer)
      return
    }
    scrollbarRef.value.setScrollTop(tempHeight)
  }, 300 / 60)
}
</script>

<style lang="scss" scoped>
.WaterfallItem {
  p {
    text-align: center;
  }
  .item {
    position: relative;
    overflow: hidden;
    .imgbg {
      width: 100%;
      height: 100%;
      border-radius: 5px !important;
      object-fit: cover;
    }
  }
}
.btn {
  cursor: pointer;
  position: fixed;
  right: 50px;
  bottom: 20px;
}
.icon {
  width: 35px;
  height: 35px;
}
</style>